const jsonServer = require('json-server')
const path = require('path')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'mock/db.json'))
const middlewares = jsonServer.defaults()

server.use((req, res, next) => {
  // Converts POST to GET and move payload to query params
  // This way it will make JSON Server that it's GET request
  if (req.method !== 'GET') {
    req.method = 'GET'
  }
  req.query = {} // 该行代码可以清空查询参数，但是发现 自定义路由映射的只要带了查询参数就出错

  // 所以这里重定向到没有参数的路径
  if (req.url.includes('?')) {
    res.redirect(req.url.replace(/\?.*$/, ''))
    return
  }
  // Continue to JSON Server router
  next()
})

server.use(middlewares)
server.use('/api', router)
// server.use(router)
router.render = (req, res) => {
  // console.log(res)
  res.jsonp({
    code: 200,
    msg: 'success',
    data: res.locals.data
  })
}

server.listen(3001, () => {
  console.log('JSON Server is running')
})
